<template>
  <div class="pwd-panel">
    <div class="pwd-hearder flex-between">
      <div class="logo-contanier flex-column flex-y-center">
        <img src="../../../common/assets/images/kangni_logo1.jpg" />
        <!-- <span>SRM供应商管理云平台</span> -->
      </div>
      <div class="account-container flex-row">
        <el-link type="info" :underline="false" class="has-account">已有账号？</el-link>
        <el-link :underline="false" style="color: #fff" @click="handleLogIn"
          >立即登录<i class="el-icon-caret-right"></i>
        </el-link>
      </div>
    </div>

    <div class="pwd-content">
      <x-sub-page :isShowBack="true" :content="title" @goBack="goBack">
        <el-form
          class="user-form"
          :model="userForm"
          :hide-required-asterisk="true"
          ref="ruleFormRef"
          :rules="rules"
          label-position="top"
          @submit.native.prevent
        >
          <el-form-item :label="$t('login.moblie')" prop="mobile">
            <el-input
              v-model="userForm.mobile"
              auto-complete="off"
              :placeholder="$t('login.mobliePlaceholder')"
              type="text"
            />
          </el-form-item>
          <el-form-item :label="$t('login.verificationCode')" prop="captcha">
            <x-code-input
              ref="codeInput"
              v-model="userForm.captcha"
              :type="'moblie'"
              :isRandom="false"
              @refreshCode="getAuthCode"
              @handleEnter="onSubmit()"
              :placeholder="$t('login.moblieCode')"
            />
          </el-form-item>
          <el-form-item :label="$t('login.newPwd')" prop="newPwd">
            <el-input
              v-model="userForm.newPwd"
              auto-complete="off"
              :placeholder="$t('login.pwdRule')"
              type="password"
              @keyup.enter.native="onSubmit()"
            />
          </el-form-item>
          <el-form-item :label="$t('login.confirmPwd')" prop="password">
            <el-input
              v-model="userForm.password"
              auto-complete="off"
              :placeholder="$t('login.confirmPwdText')"
              type="password"
              @keyup.enter.native="onSubmit()"
            />
          </el-form-item>
          <el-form-item label-width="76px">
            <el-button type="primary" :loading="loading" size="medium" style="width: 100%" @click.prevent="onSubmit()">
              {{ $t('login.submit') }}
            </el-button>
          </el-form-item>
        </el-form>
      </x-sub-page>
      <div class="footer-link"> </div>
    </div>
  </div>
</template>
<script>
  import { throttle, checkMobilePhone, checkPwd, encrypt } from '@package/utils'
  import { apiPutFogetPwd, apiGetMobileCode } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    name: 'ForgetPwd',
    data() {
      return {
        title: '重置密码',
        userForm: {
          captcha: '',
          captchaKey: '',
          mobile: '',
          newPwd: '',
          password: ''
        },
        rules: {
          mobile: [
            { required: true, trigger: 'blur', message: '请输入手机号码' },
            { validator: this.validatePhone, trigger: 'blur' }
          ],
          captcha: [
            { required: true, trigger: 'blur', message: '请输入验证码' },
            { validator: this.checkMobliedCode, trigger: 'blur' }
          ],
          newPwd: [
            { required: true, message: this.$t('system.user.enterPassword'), trigger: 'blur' },
            { min: 6, max: 50, message: this.$t('system.user.pwdLengthPlaceholder'), trigger: 'blur' },
            { validator: this.validatePwd, trigger: 'blur' }
          ],
          password: [
            { required: true, message: this.$t('system.user.enterPassword'), trigger: 'blur' },
            { validator: this.validateConfimPwd, trigger: 'blur' }
          ]
        },
        loading: false,
        verificationCode: ''
      }
    },
    methods: {
      getAuthCode() {
        this.$refs.ruleFormRef.validateField('mobile', (valid) => {
          if (!valid) {
            const formData = new FormData()
            formData.append('mobile', this.userForm.mobile)
            this.$refs.codeInput.refreshTimes()
            apiGetMobileCode(formData).then(({ data }) => {
              this.$message.success(`验证码已发，请注意查收！${data.captcha}`)
              this.verificationCode = data.captcha
              this.userForm.captchaKey = data.captchaKey
            })
          }
        })
      },
      validatePhone(rule, value, callback) {
        if (value && value !== '' && !checkMobilePhone(value)) {
          callback(new Error(this.$t('system.user.PleasePhoneRight')))
        } else {
          callback()
        }
      },
      validatePwd(rule, value, callback) {
        if (value && value !== '' && !checkPwd(value)) {
          callback(new Error(this.$t('system.user.PasswordMode')))
        } else {
          callback()
        }
      },
      validateConfimPwd(rule, value, callback) {
        if (value && value !== '' && value !== this.userForm.newPwd) {
          callback(new Error(this.$t('login.confirmPwdTips')))
        } else {
          callback()
        }
      },
      /**
       * @param codeForm - 重设密码
       * 提交表单
       */
      onSubmit: throttle(function () {
        this.loading = true
        this.$refs.ruleFormRef.validate(async (valid, error) => {
          if (valid) {
            this.loading = true
            const formData = new FormData()
            formData.append('mobile', this.userForm.mobile)
            formData.append('captcha', this.userForm.captcha)
            formData.append('password', encrypt(this.userForm.password))
            formData.append('captchaKey', this.userForm.captchaKey)
            try {
              const { code } = await apiPutFogetPwd(formData)
              if (code === EnumApiCode.Success) {
                this.loading = false
                this.$router.push('/resetSuccess')
              }
            } catch (e) {
              this.loading = false
            }
          } else {
            this.getAuthCode()
            this.loading = false
          }
        })
      }, 1000),
      goBack() {
        this.$router.go(-1)
      },
      handleLogIn() {
        this.$router.push({ path: '/login' })
      }
    }
  }
</script>
<style lang="scss" scoped>
  ::v-deep.pwd-panel .x-sub-page-container {
    width: 60%;
    height: 80%;
  }
</style>
<style lang="scss" scoped>
  @import '../style/login';
</style>
